package com.ftar.urgent.audiorecord;

import android.media.AudioFormat;
import android.os.Build;
import android.util.Log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

public class FTAudioRecordManager {

    private static volatile FTAudioRecordManager instance;

    private Map<FTAudioRecordCallback, FTAudioRecord> mRecordMap = new ConcurrentHashMap<>(10);
    private FTAudioRecord mAudioRecord;
    private List<FTAudioRecordCallback> audioCallback = new CopyOnWriteArrayList<>();

    private FileOutputStream fos;
    private boolean debugLog = false;

    public void openDebug() {
        getInstance().debugLog = true;
    }

    public void closeDebug() {
        getInstance().debugLog = false;
    }

    public static int AUDIO_CHANNEL = AudioFormat.CHANNEL_IN_STEREO;
    public static int AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
    public static int SAMPLE_RATE = 8000;

    private FTAudioRecordManager() {
    }

    public static FTAudioRecordManager getInstance() {
        if (instance == null) {
            instance = new FTAudioRecordManager();
        }
        return instance;
    }

    private final FTAudioRecordCallback defaultCallback = new FTAudioRecordCallback() {
        @Override
        public void onDataRecv(byte[] buffer, int bufferLen) {
            writeDataTOFile(buffer);
            for (FTAudioRecordCallback rkAudioRecordCallback : audioCallback) {
                rkAudioRecordCallback.onDataRecv(buffer, bufferLen);
            }
        }
    };

    public void configAudioRecordParams(int bitrate,int channel, int format){
        AUDIO_CHANNEL = channel;
        AUDIO_FORMAT = format;
        SAMPLE_RATE = bitrate;
    }

    public void startRecord(FTAudioRecordCallback callback) {

        if (mRecordMap.containsKey(callback)) {
            return;
        }
        if (isSupportMultiMic()) {
            FTAudioRecord FTAudioRecord = new FTAudioRecord();
            FTAudioRecord.startRecord(callback);
            mRecordMap.put(callback, FTAudioRecord);

        } else {
            if (null == mAudioRecord) {
                mAudioRecord = new FTAudioRecord();
                mAudioRecord.AUDIO_CHANNEL = AUDIO_CHANNEL;
                mAudioRecord.AUDIO_FORMAT = AUDIO_FORMAT;
                mAudioRecord.SAMPLE_RATE = SAMPLE_RATE;
                mAudioRecord.startRecord(defaultCallback);
            }
            if (!audioCallback.contains(callback)) {
                audioCallback.add(callback);
            }
        }

    }

    private boolean isSupportMultiMic() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q;
    }

    public void stopRecord(FTAudioRecordCallback callback) {
        if (isSupportMultiMic()){
            if (null != callback) {
                FTAudioRecord FTAudioRecord = mRecordMap.get(callback);
                if (null != FTAudioRecord) {
                    FTAudioRecord.stopRecord();
                }
                mRecordMap.remove(callback);
            }
        } else {
            audioCallback.remove(callback);
            if (audioCallback.size() == 0 && null != mAudioRecord) {
                mAudioRecord.stopRecord();
                mAudioRecord = null;
            }
        }
    }

    public void createRecordFile(String filePath) {
        fos = null;
        try {
            String currentFileName = "audioSys";

            File file = new File(filePath);
            if (file.exists()) {
//                file.delete();
            }
            fos = new FileOutputStream(file);// 建立一个可存取字节的文件
        } catch (IllegalStateException e) {
            Log.e("AudioRecorder", e.getMessage());
            throw new IllegalStateException(e.getMessage());
        } catch (FileNotFoundException e) {
            Log.e("AudioRecorder", e.getMessage());

        }

    }

    /**
     * 将音频信息写入文件
     *
     */
    private void writeDataTOFile(byte[] audioData) {

        if(fos != null) {
            try {
                fos.write(audioData);
//            if (fos != null) {
//                fos.close();// 关闭写入流
//            }
            } catch (IOException e) {
                Log.e("AudioRecorder", e.getMessage());
            }
        }
    }
}
